<?php
//session_start();
//include_once $_SERVER['DOCUMENT_ROOT']."/math-videos/configure.inc.php";
//check if you have curl loaded
//echo $_REQUEST['json'];
//echo "@@@@@@@@@@@@";
//echo "valid_controller=$valid_controller<bR>";
if(!isset($valid_controller)||$valid_controller===false)
{
  return;
}

$user_id='';
$institute_id='';

if(isset($_REQUEST['assetID'] ) && $_REQUEST['assetID'] !='' && is_numeric($_REQUEST['assetID']))
{
 $assetID = $_REQUEST['assetID'];
}
else
{
	
	$data_string = json_decode($_REQUEST['json']);  
	 //echo "data_string=$data_string".'<br>'; 
	foreach($data_string as $key=>$value)
	{
		$$key = trim($value);
		//	 echo "$key=$value".'<br>';
		/* if($key=='username')
		 {
			 $username = base64_decode($value);
		 }
		 if($key=='password')
		 {
			 $password = base64_decode($value);
		 }*/
	}  
}
// echo "assetID=$assetID".'<br>';
if($assetID=='')//catalog retrive
{
	if($username !='' && $password !='')
	{
		//authertication user
		$sqltext="select id as user_id, institute_id from users  WHERE username=? and password=?";
		$params = array();
		
		array_push($params,sql_escape($username));
		array_push($params,sql_escape($password));
		$result = db_select_query($conn2,$sqltext,$params);
		$user_id='';
		while($row = db_fetch_array($result))
		{
			$user_id = $row['user_id'];
			$institute_id = $row['institute_id'];
			//$_SESSION['http_logged']=1;
		}
	}

	if($user_id =='')
	{
		header('HTTP/1.1 400 Insufficient Permissions ');
	//	echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
	//	echo "Location: https://api.mathinstitutes.org/metadata/v1/asset/2341<br />";
		echo "{\"error\": \"Insufficient Permissions\"}";
	}
	else
	{
		$sqltext="select id as assetID,
										assetSHA1,
										timecodeSHA1,
										thumbnailSHA1,
										statisticsSHA1
											from asset WHERE institute_id=?";
		$params = array();
		
		array_push($params,sql_escape($institute_id));
		$result = db_select_query($conn,$sqltext,$params);
		if(db_num_rows($result)<1)
		{
			//echo "Error 404 AssetId Not Found!";
			header('HTTP/1.1 404 Asset Not Found');
		//	echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
			echo "{\"error\": \"Asset Not Found.\"}";
		}
		else
		{
			unset($result_array);
			$num_i=0;
			while($row = db_fetch_object($result))
			{
				foreach ($row as $key => $value) 
				{
					$value = trim($value);
					$result_array[$num_i][$key]=$value;	
							
				}
				$num_i++;
			}
			//add to api log
			$sqltext="INSERT INTO api_logs(query,added_date,user_id, institute_id) values( ?, ?, ?,?)";
			$params = array();
			array_push($params,'Select Catalog');
			array_push($params,date("Y-m-d H:i:s"));
			array_push($params,sql_escape($user_id));
			array_push($params,sql_escape($institute_id));
			db_change_query($conn,$sqltext,$params);
			header('HTTP/1.1 200 OK');
		//	echo "HTTP/1.1 200 OK <br />";
		//  echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
		//	echo "Content-Type: application/json<br />";
		//	echo "Location: ".$site_http."metadata/v1/asset/$id<br />";
		//	@header ("content-type: text/json charset=utf-8");
		  $result=json_encode($result_array);
			if(isset($_REQUEST['callback']))
			{  
				echo $_REQUEST['callback']. '(' . $result . ');';
				return;
			}
			echo $result;
			
		}
	}
}
else// get one asset informatjion
{
	$id= $assetID;
	if($username !='' && $password !='')
	{
		//authertication user
		$sqltext="select id as user_id, institute_id from users  WHERE username=? and password=?";
		$params = array();
		
		array_push($params,sql_escape($username));
		array_push($params,sql_escape($password));
		$result = db_select_query($conn2,$sqltext,$params);
		$user_id='';
		while($row = db_fetch_array($result))
		{
			$user_id = $row['user_id'];
			$institute_id = $row['institute_id'];
			//$_SESSION['http_logged']=1;
		}
	}
	if($user_id !='' && $institute_id !='')
	{
		$sqltext="INSERT INTO api_logs(query,added_date,user_id, institute_id,asset_id) values( ?, ?, ?,?,?)";
		$params = array();
		array_push($params,'Select asset');
		array_push($params,date("Y-m-d H:i:s"));
		array_push($params,sql_escape($user_id));
		array_push($params,sql_escape($institute_id));
		array_push($params,sql_escape($id));
		db_change_query($conn,$sqltext,$params);
	}
	
	$sqltext="select title, 
										abstract, 
										to_char(asset.lecture_date,'mm/dd/yyyy') as lecture_date,  
										duration, 
										asset_type, 
										abstract_url, 
										remote_url, 
										location, 
										event_title, 
									/*	to_char(asset.created_datetime,'mm/dd/yyyy') as created_datetime, 
								    created_by,
										to_char(asset.last_modified_datetime,'mm/dd/yyyy') as last_modified_datetime,
										 last_modified_by,*/
										rating, 
										views,
										thumbnail,
										thumbnail_type,
										assetSHA1,
										timecodeSHA1,
										statisticsSHA1,
										thumbnailSHA1
										from asset WHERE id=?";
	$params = array();
	
	array_push($params,sql_escape($id));
//	array_push($params,sql_escape($user_id));
	$result = db_select_query($conn,$sqltext,$params);
	if(db_num_rows($result)<1)
	{
		//echo "Error 404 AssetId Not Found!";
	//	echo "HTTP/1.1 404, 403 <br />";
		 header('HTTP/1.1 404, 403 Asset Not Found OR Insufficient Permissions');
  	//echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
		echo "{\"error\": \"Asset Not Found OR Insufficient Permissions.\"}";
	}
	else
	{
		unset($result_array);
		unset($presenter_array);
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				if($key=='lecture_date')
				{
					$value = strtotime($value);
					$key='lectureDate';
				}
				elseif($key=='asset_type')
				{
					 $key='type';
				}
				elseif($key=='abstract_url')
				{
					 $key='abstractURL';
				}
				elseif($key=='remote_url')
				{
					 $key='remoteURL';
				}
				elseif($key=='event_title')
				{
					 $key='eventTitle';
				}
				elseif($key=='assetsha1')
				{
					 $key='assetSHA1';
				}
				elseif($key=='statisticssha1')
				{
					 $key='statisticsSHA1';
				}
				elseif($key=='thumbnailsha1')
				{
					 $key='thumbnailSHA1';
				}
				elseif($key=='timecodesha1')
				{
					 $key='timecodeSHA1';
				}
				$$key = $value;
				$result_array[$key]=$value;		
				
			}
			
		}
/*		$sqltext="select username from users  WHERE id=?";
		$params = array();
		
		array_push($params,sql_escape($created_by));
		$result = db_select_query($conn2,$sqltext,$params);
		while($row = db_fetch_array($result))
		{
			$result_array['created_by']=$row['username'];
		}
		$sqltext="select username from users  WHERE id=?";
		$params = array();
		
		array_push($params,sql_escape($last_modified_by));
		$result = db_select_query($conn2,$sqltext,$params);
		while($row = db_fetch_array($result))
		{
			$result_array['last_modified_by']=$row['username'];
		}*/
		if($thumbnail_type !='' && $thumbnail!='')//has thumbail
		{
		 unset($result_array['thumbnail_type']);
		 unset($result_array['thumbnail']);
		 $result_array['thumbnail']['type']=$thumbnail_type;
		 $result_array['thumbnail']['localURL']=$site_http.'images/'.$thumbnail;
		}
	//get presenter
		$sqltext="SELECT first_name, last_name, middle_name, alt_name, suffix, title, department, organization as company FROM presenter  WHERE asset_id= ?";
		$params = array();
		array_push($params,sql_escape($id));
		$result = db_select_query($conn,$sqltext,$params);
		$num=0;
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				//$$key = $value;
				//$presenter_array[$key]=$value;
				if($key=='first_name')
				{
					 $key='givenName';
				}
				if($key=='last_name')
				{
					 $key='familyName';
				}
				if($key=='middle_name')
				{
					 $key='middleName';
				}
				if($key=='alt_name')
				{
					 $key='altName';
				}
				$result_array["presenters"][$num][$key]=$value;
			}
			$num++;
		}
	
			//get keywords
			
		$sqltext="SELECT keyword FROM keyword  WHERE asset_id= ?";
		$params = array();
		array_push($params,sql_escape($id));
		$result = db_select_query($conn,$sqltext,$params);
		$num=0;
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				//$$key = $value;
				//$result_array[$key]=$value;
				$result_array['keywords'].=$value.",";
			}
			$num++;
		}
		if(isset($result_array['keywords']))
		{
			$result_array['keywords']=substr($result_array['keywords'],0,strlen($result_array['keywords'])-1);
		}
			//get timecode
		$sqltext="SELECT timecode, timecode_type as type, data FROM timecode  WHERE asset_id= ?";
		$params = array();
		array_push($params,sql_escape($id));
		$result = db_select_query($conn,$sqltext,$params);
		$num=0;
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				//$$key = $value;
				$result_array['timecodeData'][$num][$key]=$value;
			}
			$num++;
		}
		
				//get msc_number
		$sqltext="SELECT msc FROM msc_number  WHERE asset_id= ?";
		$params = array();
		array_push($params,sql_escape($id));
		$result = db_select_query($conn,$sqltext,$params);
		$num=0;
		while($row = db_fetch_object($result))
		{
			foreach ($row as $key => $value) 
			{
				$value = trim($value);
				//$$key = $value;
				///$result_array[$key]=$value;
				$result_array['mscNumbers'].=$value.",";
			}
			$num++;
		}
		if(isset($result_array['mscNumbers']))
		{
			$result_array['mscNumbers']=substr($result_array['mscNumbers'],0,strlen($result_array['mscNumbers'])-1);
		}
		$result_array["assetID"]=$id;
		header('HTTP/1.1  200 OK');
		//echo "HTTP/1.1 200 OK <br />";
		//echo "Date: ".gmdate('F j, Y, g:i:s')." GMT<br />";
	//	echo "Content-Type: application/json<br />";
	//	echo "Location: ".$site_http."metadata/v1/asset/$id<br />";
	//	@header ("content-type: text/json charset=utf-8");
		$result=json_encode($result_array);
		if(isset($_REQUEST['callback']))
		{  
			echo $_REQUEST['callback']. '(' . $result . ');';
			return;
		}
		echo $result;
	
	//	echo "<br>";
	//	echo "{ <br />".displayTree($result_array)."<br/>}";
		
		//return json array
		/*$result_array = array("title" => "$title", 
					"lecture_date"=> "$lecture_date",
					"remote_url" => "$remote_url",
					"organization" => "$organization",
					"presenter" => "$first_name $last_name",
					"job_title" => "$job_title",
					"keyword" => "$keyword",
					"timecode" => "$timecode",
					"timecode_type" => "$timecode_type",
					"data" =>"$data",
					"assetID" =>"$id"
					); */
	//	print_r($result_array);  
	/* Setting up JSON headers */
							//	@header ("content-type: text/json charset=utf-8");
	
								/* Printing the JSON Object */
						//	echo json_encode($result_array);  
							//	echo json_decode(json_encode($result_array));  
								//	print_r( $result_array); 
		}
//}
	/*function displayTree($array) {
			 $newline = "<br>";
			 foreach($array as $key => $value) {    //cycle through each item in the array as key => value pairs
					 if (is_array($value) || is_object($value)) {        //if the VALUE is an array, then
							//call it out as such, surround with brackets, and recursively call displayTree.
							 $value = "{<ul>" . displayTree($value) . "</ul>&nbsp;&nbsp;&nbsp;}";
					 }
					//if value isn't an array, it must be a string. output its' key and value.
					$output .= "&nbsp;&nbsp;&nbsp;\"$key\": " . $value . $newline;
			 }
			 return $output;
	}*/
}
?>